package name.marz.to.go.ahg;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;

import name.marz.to.go.ahg.common.cli.OutDirOption;
import name.marz.to.go.ahg.common.cli.PasswordOption;
import name.marz.to.go.ahg.common.util.HttpUtil;
import name.marz.to.go.ahg.common.util.LogUtil;
import name.marz.to.go.ahg.core.AbstractAutoGetterMain;
import name.marz.to.go.ahg.core.AutoGetterHttpClient;
import name.marz.to.go.ahg.core.exception.UserProcessException;
import name.marz.to.go.ahg.core.executer.AbstractLoginExecuter;
import name.marz.to.go.ahg.core.executer.DocumentGetExecuter;
import name.marz.to.go.ahg.core.executer.Executer;
import name.marz.to.go.ahg.mufgbk.MUFGbkClient;
import name.marz.to.go.ahg.mufgbk.executer.MUFGbkCSVDownloader;
import name.marz.to.go.ahg.mufgbk.executer.MUFGbkDetailPageExecuter;
import name.marz.to.go.ahg.mufgbk.executer.MUFGbkDownloadPageExecuter;
import name.marz.to.go.ahg.mufgbk.executer.MUFGbkLoginExecuter;
import name.marz.to.go.ahg.mufgbk.executer.MUFGbkLogoutExecuter;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.http.client.ClientProtocolException;
import org.jsoup.nodes.Document;


public class MUFGbkGetMain extends AbstractAutoGetterMain {

	private static final Logger log = Logger.getLogger(MUFGbkGetMain.class.getName());
	private static final String DEFAULT_MEISAI_DIRNAME=".";
	
	private AutoGetterHttpClient client = new MUFGbkClient();
	
	private String userId;
	private String password;
	private File outDir;
	
	/**
	 * 
	 */
	public MUFGbkGetMain() {
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		MUFGbkGetMain main = new MUFGbkGetMain();
		main.Main(args);
	}

	/* (non-Javadoc)
	 * @see name.marz.to.go.ahg.core.AbstractMain#ready()
	 */
	@Override
	protected void ready() throws Exception {
		super.ready();
		LogUtil.log(Level.FINE, client.getCookieStore().getCookies());
	}

	@Override
	public Document goTopPage() throws ClientProtocolException, IOException, UserProcessException {
		// トップページ処理
		URI uri = HttpUtil.createURISafety("https://entry11.bk.mufg.jp/ibg/dfw/APLIN/loginib/login?_TRANID=AA000_001");
		Document doc = new DocumentGetExecuter(uri, client, "トップページ").execute();
		LogUtil.log(Level.FINE, client.getCookieStore().getCookies());
		LogUtil.log(Level.FINE, HttpUtil.getParametersFromInputTags(doc),"top page params");
		return doc;
	}

	@Override
	public Document doLogin(Document doc) throws ClientProtocolException, IOException, UserProcessException {
		// ログイン処理
		URI uri = HttpUtil.createURISafety("https://entry11.bk.mufg.jp/ibg/dfw/APLIN/loginib/login?_TRANID=AA000_001");
		AbstractLoginExecuter le = new MUFGbkLoginExecuter(uri, client, doc);
		le.setUserIdentifiers( new String[] { userId } );
		le.setUserPass( password );
		doc = le.execute();
		log.finer("login response source="+doc.html());
		return doc;
		// TODO:メッセージがあるときの処理
	}

	@Override
	public Document goDownloadPage(Document doc) 	throws ClientProtocolException, IOException, UserProcessException {
		// 利用明細確認
		log.info("入出金明細照会 開始");
		URI uri = HttpUtil.createURISafety("https://direct11.bk.mufg.jp/ib/dfw/APL/bnkib/banking");
		Executer<Document> de = new MUFGbkDetailPageExecuter(uri, client, doc);
		doc = de.execute();
		log.finer("detail response source="+doc.html());
		LogUtil.log(Level.FINER, HttpUtil.getParametersFromFormTag(doc, "MainForm"), "detail response params");
		log.info("入出金明細照会 終了");
		// 明細ダウンロードページへの遷移
		log.info("明細CSVのダウンロードページ遷移 開始");
		Executer<Document> dlpe = new MUFGbkDownloadPageExecuter(uri, client, doc);
		doc = dlpe.execute();
		log.finer("download response source="+doc.html());
		log.info("明細CSVのダウンロードページ遷移 終了");
		return doc;
	}

	@Override
	public File doDownload(Document doc) throws ClientProtocolException, IOException, UserProcessException {
		// 明細ダウンロード
		URI uri = HttpUtil.createURISafety("https://direct11.bk.mufg.jp/ib/dfw/APL/bnkib/banking");
		Executer<File> dle = new MUFGbkCSVDownloader(uri, client, outDir, doc);
		return dle.execute();
	}

	@Override
	public void doLogout(Document doc) throws ClientProtocolException, IOException, UserProcessException {
		URI uri = HttpUtil.createURISafety("https://direct11.bk.mufg.jp/ib/dfw/APL/bnkib/banking");
		Executer<Document> loe = new MUFGbkLogoutExecuter(uri, client, doc);
		doc = loe.execute();
	}

	@SuppressWarnings("static-access")
	@Override
	protected Options getOptions() {
		Options options = new Options();
		Option out = new OutDirOption(false);options.addOption(out);
		options.addOption(OptionBuilder.hasArg(true).withArgName("KEIYAKU NO")
				.isRequired(true).withDescription("ご契約番号")
				.create("keiyakuno"));
		Option password = new PasswordOption(true); options.addOption(password);
		return options;
	}

	@Override
	protected void setParams(CommandLine cmd) {
		userId = cmd.getOptionValue("keiyakuno");
		this.password = cmd.getOptionValue(PasswordOption.OPT);
		outDir = new File(cmd.getOptionValue(OutDirOption.OPT, DEFAULT_MEISAI_DIRNAME));
	}

}
